import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Button, 
  message, 
  Space,
  Typography,
  Tag,
  Input,
  Row,
  Col,
  Modal,
  Descriptions,
  Divider
} from 'antd';
import { 
  SearchOutlined,
  CloudSyncOutlined,
  FileTextOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import { getFunctions, deployFunction } from '../../services/api';

const { Title, Text } = Typography;
const { Search } = Input;

const FunctionStore = () => {
  const [functions, setFunctions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedFunction, setSelectedFunction] = useState(null);
  const [isModalVisible, setIsModalVisible] = useState(false);

  const fetchPublishedFunctions = async (keyword = '') => {
    try {
      setLoading(true);
      const response = await getFunctions(keyword, true); // true表示只获取已发布的函数
      setFunctions(response.data.functions);
    } catch (error) {
      message.error('获取函数列表失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPublishedFunctions();
  }, []);

  const handleDeploy = async (id) => {
    try {
      const response = await deployFunction(id);
      message.success(response.data.message);
    } catch (error) {
      message.error('部署函数失败: ' + error.message);
    }
  };

  const handleSearch = (value) => {
    setSearchKeyword(value);
    fetchPublishedFunctions(value);
  };

  const showModal = (func) => {
    setSelectedFunction(func);
    setIsModalVisible(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setSelectedFunction(null);
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleString();
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Title level={3}>函数商店</Title>
      </div>
      
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} md={8} lg={6}>
          <Search
            placeholder="搜索函数名称、描述或Handler"
            allowClear
            enterButton={<SearchOutlined />}
            onSearch={handleSearch}
            onClear={() => handleSearch('')}
          />
        </Col>
      </Row>
      
      <Row gutter={[16, 16]}>
        {functions.map((func) => (
          <Col xs={24} sm={12} md={8} lg={6} key={func.id}>
            <Card
              cover={
                <div style={{ 
                  backgroundColor: '#f0f2f5', 
                  height: 120, 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center' 
                }}>
                  <FileTextOutlined style={{ fontSize: 48, color: '#1890ff' }} />
                </div>
              }
              actions={[
                <Button 
                  type="primary" 
                  icon={<InfoCircleOutlined />} 
                  onClick={() => showModal(func)}
                  block
                >
                  查看详情
                </Button>,
                <Button 
                  type="default" 
                  icon={<CloudSyncOutlined />} 
                  onClick={() => handleDeploy(func.id)}
                  block
                >
                  部署
                </Button>
              ]}
            >
              <Card.Meta
                title={
                  <Space>
                    {func.name}
                    {func.version && <Tag color="blue">{func.version}</Tag>}
                  </Space>
                }
                description={
                  <div>
                    <Text ellipsis={{ tooltip: func.description }} style={{ display: 'block' }}>
                      {func.description || '暂无描述'}
                    </Text>
                    <Text type="secondary" style={{ fontSize: '12px', marginTop: 8, display: 'block' }}>
                      创建时间: {formatDate(func.createdAt)}
                    </Text>
                  </div>
                }
              />
            </Card>
          </Col>
        ))}
      </Row>
      
      {functions.length === 0 && !loading && (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Text type="secondary">暂无已发布的函数</Text>
        </div>
      )}
      
      <Modal
        title="函数详情"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={800}
        footer={[
          <Button key="deploy" type="primary" onClick={() => {
            handleDeploy(selectedFunction?.id);
            handleCancel();
          }}>
            部署函数
          </Button>,
          <Button key="close" onClick={handleCancel}>
            关闭
          </Button>
        ]}
      >
        {selectedFunction && (
          <div>
            <Descriptions title="基本信息" column={1} bordered>
              <Descriptions.Item label="函数名称">{selectedFunction.name}</Descriptions.Item>
              <Descriptions.Item label="版本">{selectedFunction.version || 'v1.0.0'}</Descriptions.Item>
              <Descriptions.Item label="描述">{selectedFunction.description || '暂无描述'}</Descriptions.Item>
              <Descriptions.Item label="Handler">{selectedFunction.handler}</Descriptions.Item>
              <Descriptions.Item label="镜像">{selectedFunction.image}</Descriptions.Item>
              <Descriptions.Item label="执行时限">{selectedFunction.timeout ? `${selectedFunction.timeout}秒` : '30秒'}</Descriptions.Item>
              <Descriptions.Item label="创建时间">{formatDate(selectedFunction.createdAt)}</Descriptions.Item>
              <Descriptions.Item label="更新时间">{formatDate(selectedFunction.updatedAt)}</Descriptions.Item>
            </Descriptions>
            
            <Divider />
            
            <Descriptions title="资源配置" column={1} bordered>
              <Descriptions.Item label="请求资源">
                {selectedFunction.requests && Object.keys(selectedFunction.requests).length > 0 
                  ? JSON.stringify(selectedFunction.requests) 
                  : '默认配置'}
              </Descriptions.Item>
              <Descriptions.Item label="资源限制">
                {selectedFunction.limits && Object.keys(selectedFunction.limits).length > 0 
                  ? JSON.stringify(selectedFunction.limits) 
                  : '默认配置'}
              </Descriptions.Item>
            </Descriptions>
            
            <Divider />
            
            <div>
              <h3>环境变量</h3>
              {selectedFunction.env && Object.keys(selectedFunction.env).length > 0 ? (
                <Descriptions column={1} bordered>
                  {Object.entries(selectedFunction.env).map(([key, value]) => (
                    <Descriptions.Item label={key} key={key}>
                      {String(value)}
                    </Descriptions.Item>
                  ))}
                </Descriptions>
              ) : (
                <Text type="secondary">暂无环境变量配置</Text>
              )}
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default FunctionStore;